package com.hjj.listener;

import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

@WebListener
public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 获取全局变量的值
        ServletContext servletContext = sce.getServletContext();
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        System.out.println("Tomcat启动了...................." + contextConfigLocation);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Tomcat关闭了...................");

        // 使用DriverManager获取所有驱动
        Enumeration<Driver> drivers = DriverManager.getDrivers();

        // 迭代drivers
        while(drivers.hasMoreElements()){
            try {
                // 销毁掉所有的驱动
                DriverManager.deregisterDriver(drivers.nextElement());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 再关闭AbandonedConnectionCleanupThread线程
        AbandonedConnectionCleanupThread.checkedShutdown();
    }
}
